package com.example.javaservice.service;

import com.example.javaservice.mapper.UserMapper;
import com.example.javaservice.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private final UserMapper userMapper;
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md.digest(password.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /** 注册 */
    public boolean register(User user) {
        User exist = userMapper.findByUsername(user.getUsername());
        if (exist != null) {
            return false; // 用户名已存在
        }
        user.setPassword(hashPassword(user.getPassword()));
        return userMapper.insert(user) > 0;
    }

    /** 登录 */
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        String hashedInput = hashPassword(password);
        if (Objects.equals(user.getPassword(), hashedInput)) {
            return user;
        }
        return null;
    }
}
